<template>
	<div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">我的</h1>
				</section>
			</div>
		</header>

		<!-- 主要内容区域 -->
		<div class="main-content">
			<!-- 用户信息和钱包卡片 -->
			<div class="user-wallet-container">
				<!-- 用户信息卡片 -->
				<div class="user-card" @click="checkLoginAndRedirect">
					<div class="user-header">
						<div class="avatar-container">
							<img 
								v-if="hasAvatar && !avatarError"
								:src="getAvatar(user.userImg)" 
								:alt="user.userName || '用户头像'"
								class="user-avatar"
								@error="handleAvatarError"
							>
							<i v-else class="material-icons default-avatar-icon">account_circle</i>
						</div>
					<div class="user-info">
						<h2 class="user-name">{{ user.userName || '未登录' }}</h2>
						<p class="user-id">{{ user.userId || '' }}</p>
						<div class="user-level-info" v-if="user.level">
							<span class="level-badge" @click.stop="toLevelInfo">
								<i class="material-icons level-icon">military_tech</i>
								Lv{{ user.level }}
							</span>
							<span class="discount-badge" @click.stop="toLevelInfo">
								<i class="material-icons discount-icon">local_offer</i>
								{{ user.discount }}折
							</span>
							<span class="super-member-badge" v-if="isSuperMember" @click.stop="toSuperMember">
								<i class="material-icons">stars</i>
								超级会员
							</span>
						</div>
						<div class="user-level-info" v-else>
							<span class="level-badge" @click.stop="toLevelInfo">
								<i class="material-icons level-icon">military_tech</i>
								Lv1
							</span>
							<span class="discount-badge" @click.stop="toLevelInfo">
								<i class="material-icons discount-icon">local_offer</i>
								99折
							</span>
							<span class="super-member-badge" v-if="isSuperMember" @click.stop="toSuperMember">
								<i class="material-icons">stars</i>
								超级会员
							</span>
						</div>
					</div>
					</div>
				</div>

				<!-- 钱包卡片 -->
				<div class="wallet-card-inline" @click="toMyWallet">
					<div class="wallet-icon-inline">
						<i class="material-icons">account_balance_wallet</i>
					</div>
					<div class="wallet-info-container-inline">
						<div class="wallet-info-inline">
							<p class="wallet-label-inline">钱包余额</p>
							<p class="wallet-amount-inline">¥{{ walletBalance }}</p>
						</div>
						<div class="wallet-info-inline">
							<p class="wallet-label-inline">可用额度</p>
							<p class="wallet-amount-inline">¥{{ availableCredit }}</p>
						</div>
					</div>
				</div>
				
				<!-- 积分卡片 -->
				<div class="points-card-inline" @click="toPointsStore">
					<div class="points-icon-inline">
						<i class="material-icons">stars</i>
					</div>
					<div class="points-info-container-inline">
						<div class="points-info-inline">
							<p class="points-label-inline">当前积分</p>
							<p class="points-amount-inline">{{ user.points || 0 }}</p>
						</div>
						<div class="points-info-inline">
							<p class="points-label-inline">经验值</p>
							<p class="points-amount-inline">{{ user.experiencePoints || 0 }}</p>
						</div>
					</div>
				</div>
			</div>

			<!-- 个人信息卡片 -->
			<div class="menu-card">
				<div class="menu-section">
					<h3 class="section-title">个人信息</h3>
					<div class="menu-item" @click="changeInfo(user.userId)">
						<div class="menu-item-left">
							<i class="material-icons">edit</i>
							<span>修改信息</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
					<div class="menu-item" @click="changePwd">
						<div class="menu-item-left">
							<i class="material-icons">lock</i>
							<span>修改密码</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
				</div>
			</div>

			<!-- 我的服务卡片 -->
			<div class="menu-card">
				<div class="menu-section">
					<h3 class="section-title">我的服务</h3>
					<div class="menu-item" @click="toMyWallet">
						<div class="menu-item-left">
							<i class="material-icons">account_balance_wallet</i>
							<span>我的钱包</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
					<div class="menu-item" @click="toMyCredit">
						<div class="menu-item-left">
							<i class="material-icons">stars</i>
							<span>我的积分</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
					<div class="menu-item" @click="toMyCoupons">
						<div class="menu-item-left">
							<i class="material-icons">card_giftcard</i>
							<span>我的优惠券</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
					<div class="menu-item" v-if="isConsumer" @click="toMyFavorites">
						<div class="menu-item-left">
							<i class="material-icons">favorite</i>
							<span>我的收藏</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
					<div class="menu-item" v-if="isBusiness" @click="toBusinessControl">
						<div class="menu-item-left">
							<i class="material-icons">store</i>
							<span>商品管理</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
				</div>
			</div>

			<!-- 退出登录卡片 -->
			<div class="menu-card logout-card">
				<div class="menu-section">
					<div class="menu-item logout-item" @click="logOut">
						<div class="menu-item-left">
							<i class="material-icons">logout</i>
							<span>退出登录</span>
						</div>
						<i class="material-icons">chevron_right</i>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部导航 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue'
	
	const ROLE = {
		ADMIN: 0,
		BUSINESS: 1,
		USER: 2
	};
	
	export default {
		name: 'MyInfo',
		data: function() {
			return {
				user: {},
				avatarError: false,
				walletBalance: '0.00',
				availableCredit: '0.00',
				loadingBalance: false
			}
		},
		computed: {
			hasAvatar() {
				return this.user.userImg && 
					this.user.userImg !== 'null' && 
					this.user.userImg !== '' &&
					this.user.userImg !== null;
			},
			isSuperMember() {
				if (!this.user.isSuperMember || this.user.isSuperMember === 0) {
					return false;
				}
				if (!this.user.superMemberExpireTime) {
					return false;
				}
				// 检查是否过期
				const expireTime = new Date(this.user.superMemberExpireTime);
				return expireTime > new Date();
			},
			isConsumer() {
				const role = Number(this.user && this.user.role);
				return role === ROLE.USER || Number.isNaN(role);
			},
			isBusiness() {
				const role = Number(this.user && this.user.role);
				return role === ROLE.BUSINESS;
			}
		},
		methods: {
			getImg(path){
				if(!path) return '/img/default-food.png';
				// 如果是完整的HTTP URL，直接返回
				if(path.startsWith('http')) return path;
				// 如果是 base64 格式，直接返回
				if(path.startsWith('data:image')) return path;
				// 如果是相对路径（以/开头），拼接服务器地址
				if(path.startsWith('/')) {
					// 如果已经是 /img/ 开头，直接拼接
					if(path.startsWith('/img/')) {
						return 'http://localhost:8888' + path;
					}
					// 如果是其他路径（如 /2024-10-26/xxx.jpg），需要添加 /img 前缀
					return 'http://localhost:8888/img' + path;
				}
				// 其他情况，添加服务器前缀和路径分隔符
				return 'http://localhost:8888/img/' + path;
			},
			getAvatar(userImg) {
				// 如果没有头像或头像为空，返回默认头像
				if (!userImg || userImg === 'null' || userImg === '') {
					return ''; // 返回空字符串，使用CSS的默认头像
				}
				// 如果是 base64 格式，直接返回
				if(userImg.startsWith('data:image')) return userImg;
				// 否则拼接服务器地址
				return 'http://localhost:8888' + userImg;
			},
			handleAvatarError() {
				// 头像加载失败时，显示默认头像
				this.avatarError = true;
			},
			// 跳转到修改密码页面
			changePwd() {
				this.$router.push('/changePwd');
			},
			// 检查登录状态并跳转
			checkLoginAndRedirect: function() {
				let user = this.$getSessionStorage('user');
				if (!user || user === null) {
					this.$toast?.info('请先登录');
					this.$router.push('/login');
					return;
				}
			},
			// 跳转到头像修改页面
			changeInfo: function(userId) {
				this.$router.push({path: '/changeInfo',query: {userId: userId}});
			},
			toMyCredit: function() {
				this.toPointsStore();
			},
			toPointsStore: function() {
				this.$router.push('/pointsStore');
			},
			toMyCoupons: function() {
				this.$router.push('/coupons');
			},
			toLevelInfo: function() {
				this.$router.push('/levelInfo');
			},
			toSuperMember: function() {
				this.$router.push('/superMember');
			},
			toMyWallet: function() {
				this.$router.push('/myWallet');
			},
			toMyFavorites: function() {
				// 跳转到我的收藏页面
				this.$router.push('/myFavorites');
			},
			toBusinessControl: function(){
				this.$router.push('/businessControl');
			},
			// 获取用户信息
			getUserById: function(userId) {
				let url = 'UserController/user/info';
				this.$axios.post(url, this.$qs.stringify({
						userId
					}), {
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(resp => {
						if (resp.data && (resp.data.code === 200 || resp.data.code === '200')) {
							this.user = resp.data.result || {};
							this.avatarError = false; // 重置头像错误状态
							console.log('用户信息加载成功:', this.user);
							// 加载钱包余额
							this.loadWalletBalance();
						}
					})
					.catch(err => {
						console.error('加载用户信息失败:', err);
						this.$toast?.error('加载用户信息失败');
					})
			},
			// 根据用户等级获取对应的贷款额度（与等级页面和后端保持一致）
			getLoanLimitByLevel: function(level) {
				const lv = Number(level) || 1;
				if (lv <= 1) return 500;
				if (lv === 2) return 1000;
				if (lv === 3) return 2000;
				if (lv === 4) return 3000;
				return 5000;
			},
			// 加载钱包余额
			loadWalletBalance: function() {
				if (!this.user || !this.user.userId || this.loadingBalance) return;
				
				this.loadingBalance = true;
				this.$axios.post('wallet/info', this.$qs.stringify({
					walletId: this.user.userId
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						const walletInfo = response.data.result || {};
						if (walletInfo.availableBalance) {
							this.walletBalance = walletInfo.availableBalance;
						} else if (walletInfo.balance) {
							const balance = parseFloat(walletInfo.balance || 0);
							const frozen = parseFloat(walletInfo.frozenAmount || 0);
							this.walletBalance = (balance - frozen).toFixed(2);
						} else {
							this.walletBalance = '0.00';
						}
						
						// 计算可用额度：透支额度 - 当前透支金额
						const current = parseFloat(walletInfo.currentOverdraftAmount || 0);
						// 按用户等级映射获得基础贷款额度
						const level = this.user && this.user.level ? this.user.level : 1;
						const baseLimit = this.getLoanLimitByLevel(level);
						if (baseLimit > 0) {
							const available = Math.max(0, baseLimit - current);
							this.availableCredit = available.toFixed(2);
						} else {
							this.availableCredit = '0.00';
						}
					} else {
						this.walletBalance = '0.00';
						this.availableCredit = '0.00';
					}
				}).catch(error => {
					console.error('获取钱包余额失败:', error);
					this.walletBalance = '0.00';
					this.availableCredit = '0.00';
				}).finally(() => {
					this.loadingBalance = false;
				});
			},
			// 退出登录
			logOut() {
				if (!confirm('确定要退出登录吗？')) {
					return;
				}
				this.$removeSessionStorage('user');
				let result = this.$getSessionStorage('user');
				if(result == null) {
					this.$toast?.success('退出成功');
					this.$router.push('/index');
				} else {
					this.$toast?.error('退出失败');
				}
			}
		},
		components: {
			AppFooter
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (user != null) {
				this.getUserById(user.userId);
			} else {
				this.$router.push('/login');
			}
		},
		mounted() {
		// 监听钱包余额更新事件
		if (window.addEventListener) {
			window.addEventListener('wallet-balance-updated', () => {
				if (this.user && this.user.userId) {
					setTimeout(() => {
						this.loadWalletBalance();
						this.getUserById(this.user.userId); // 刷新用户信息（包括积分）
					}, 500);
				}
			});
		}
		},
		beforeUnmount() {
			// 移除事件监听
			if (window.removeEventListener) {
				window.removeEventListener('wallet-balance-updated', this.loadWalletBalance);
			}
		}
	}
</script>

<style scoped>
	/* 重置样式 */
	* {
		box-sizing: border-box;
	}

	.wrapper {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/* 主要内容区域 */
	.main-content {
		padding: 20px 16px;
		padding-bottom: 120px; /* 为底部导航留出空间 */
	}

	/* 用户信息和钱包容器 */
	.user-wallet-container {
		display: flex;
		gap: 16px;
		margin-bottom: 24px;
		flex-wrap: wrap;
	}

	/* 用户信息卡片 */
	.user-card {
		flex: 1;
		background: linear-gradient(135deg, #1976D2 0%, #42A5F5 100%);
		border-radius: 16px;
		box-shadow: 0 4px 20px rgba(0,0,0,0.1);
		overflow: hidden;
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.user-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 24px rgba(0,0,0,0.15);
	}

	/* 钱包卡片（内联） */
	.wallet-card-inline {
		width: 200px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 16px;
		box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
		padding: 20px 16px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
		cursor: pointer;
		transition: all 0.3s ease;
		flex-shrink: 0;
	}

	.wallet-card-inline:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 24px rgba(102, 126, 234, 0.4);
	}

	.wallet-card-inline:active {
		transform: translateY(0);
	}

	.wallet-icon-inline {
		font-size: 32px;
		margin-bottom: 12px;
		opacity: 0.95;
	}

	.wallet-info-container-inline {
		display: flex;
		gap: 12px;
		width: 100%;
		justify-content: space-around;
	}

	.wallet-info-inline {
		text-align: center;
		flex: 1;
		min-width: 0;
	}

	.wallet-label-inline {
		font-size: 12px;
		opacity: 0.9;
		margin: 0 0 6px 0;
		white-space: nowrap;
	}

	.wallet-amount-inline {
		font-size: 20px;
		font-weight: bold;
		margin: 0;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	/* 积分卡片（内联） */
	.points-card-inline {
		width: 200px;
		background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
		border-radius: 16px;
		box-shadow: 0 4px 20px rgba(255, 215, 0, 0.3);
		padding: 20px 16px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
		cursor: pointer;
		transition: all 0.3s ease;
		flex-shrink: 0;
	}
	
	.points-card-inline:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 24px rgba(255, 215, 0, 0.4);
	}
	
	.points-card-inline:active {
		transform: translateY(0);
	}
	
	.points-icon-inline {
		font-size: 32px;
		margin-bottom: 12px;
		opacity: 0.95;
	}
	
	.points-info-container-inline {
		display: flex;
		gap: 12px;
		width: 100%;
		justify-content: space-around;
	}
	
	.points-info-inline {
		text-align: center;
		flex: 1;
		min-width: 0;
	}
	
	.points-label-inline {
		font-size: 12px;
		opacity: 0.9;
		margin: 0 0 6px 0;
		white-space: nowrap;
	}
	
	.points-amount-inline {
		font-size: 20px;
		font-weight: bold;
		margin: 0;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.user-header {
		padding: 32px 24px;
		display: flex;
		align-items: center;
		gap: 20px;
		color: white;
	}

	.avatar-container {
		position: relative;
		width: 80px;
		height: 80px;
		flex-shrink: 0;
	}

	.user-avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		object-fit: cover;
		border: 4px solid rgba(255, 255, 255, 0.3);
		background-color: rgba(255, 255, 255, 0.2);
		box-shadow: 0 4px 12px rgba(0,0,0,0.2);
	}

	.default-avatar-icon {
		font-size: 72px !important;
		color: rgba(255, 255, 255, 0.9) !important;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		border: 4px solid rgba(255, 255, 255, 0.3);
		box-shadow: 0 4px 12px rgba(0,0,0,0.2);
		line-height: 1;
	}

	.user-info {
		flex: 1;
		min-width: 0;
	}

	.user-name {
		font-size: 24px;
		font-weight: 500;
		margin: 0 0 8px 0;
		color: white;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.user-id {
		font-size: 16px;
		margin: 0;
		opacity: 0.9;
		color: white;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.user-level-info {
		display: flex;
		gap: 10px;
		margin-top: 12px;
		align-items: center;
		flex-wrap: wrap;
	}
	
	.level-badge {
		background: linear-gradient(135deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.2) 100%);
		color: white;
		padding: 6px 14px;
		border-radius: 16px;
		font-size: 13px;
		font-weight: 700;
		backdrop-filter: blur(10px);
		border: 1px solid rgba(255, 255, 255, 0.3);
		display: flex;
		align-items: center;
		gap: 4px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.level-badge:hover {
		background: linear-gradient(135deg, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0.3) 100%);
		transform: scale(1.05);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
	}
	
	.level-icon {
		font-size: 16px !important;
		opacity: 0.95;
	}
	
	.discount-badge {
		background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
		color: #644F1B;
		padding: 6px 14px;
		border-radius: 16px;
		font-size: 13px;
		font-weight: 700;
		display: flex;
		align-items: center;
		gap: 4px;
		box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
		border: 1px solid rgba(255, 255, 255, 0.3);
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.discount-badge:hover {
		background: linear-gradient(135deg, #FFE082 0%, #FFB74D 100%);
		transform: scale(1.05);
		box-shadow: 0 4px 12px rgba(255, 215, 0, 0.5);
	}
	
	.discount-icon {
		font-size: 16px !important;
		opacity: 0.9;
	}
	
	.super-member-badge {
		background: linear-gradient(135deg, #FF6B9D 0%, #C44569 100%);
		color: white;
		padding: 6px 14px;
		border-radius: 16px;
		font-size: 13px;
		font-weight: 700;
		display: flex;
		align-items: center;
		gap: 4px;
		box-shadow: 0 2px 8px rgba(255, 107, 157, 0.4);
		border: 1px solid rgba(255, 255, 255, 0.3);
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.super-member-badge:hover {
		background: linear-gradient(135deg, #FF8FA3 0%, #D65A7A 100%);
		transform: scale(1.05);
		box-shadow: 0 4px 12px rgba(255, 107, 157, 0.5);
	}
	
	.super-member-badge i {
		font-size: 16px !important;
		opacity: 0.95;
	}

	/* 菜单卡片 */
	.menu-card {
		background-color: white;
		border-radius: 16px;
		box-shadow: 0 4px 20px rgba(0,0,0,0.1);
		overflow: hidden;
		margin-bottom: 16px;
	}

	.logout-card {
		margin-bottom: 24px;
	}

	.menu-section {
		padding: 8px 0;
	}

	.section-title {
		font-size: 14px;
		font-weight: 500;
		color: #999;
		margin: 0;
		padding: 12px 20px 8px 20px;
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	.menu-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 20px;
		cursor: pointer;
		transition: background-color 0.2s ease;
		user-select: none;
	}

	.menu-item:hover {
		background-color: #f8f9fa;
	}

	.menu-item:active {
		background-color: #f0f0f0;
	}

	.menu-item-left {
		display: flex;
		align-items: center;
		gap: 16px;
		flex: 1;
		min-width: 0;
	}

	.menu-item-left .material-icons {
		font-size: 24px;
		color: #1976D2;
		flex-shrink: 0;
	}

	.menu-item-left span {
		font-size: 16px;
		color: #333;
		font-weight: 400;
	}

	.menu-item .material-icons:last-child {
		font-size: 24px;
		color: #ccc;
		flex-shrink: 0;
	}

	.logout-item .menu-item-left .material-icons {
		color: #f44336;
	}

	.logout-item .menu-item-left span {
		color: #f44336;
	}

	/* 响应式设计 */
	@media (max-width: 600px) {
		.main-content {
			padding: 16px 12px;
		}

		.user-wallet-container {
			flex-direction: column;
			gap: 12px;
		}

		.wallet-card-inline {
			width: 100%;
			padding: 16px;
		}
		
		.points-card-inline {
			width: 100%;
			padding: 16px;
		}

		.wallet-info-container-inline {
			gap: 8px;
		}

		.wallet-icon-inline {
			font-size: 28px;
			margin-bottom: 10px;
		}

		.wallet-label-inline {
			font-size: 11px;
		}

		.wallet-amount-inline {
			font-size: 18px;
		}
		
		.user-header {
			padding: 24px 20px;
		}
		
		.avatar-container {
			width: 64px;
			height: 64px;
		}
		
		.default-avatar-icon {
			font-size: 56px !important;
		}
		
		.user-name {
			font-size: 20px;
		}
		
		.user-id {
			font-size: 14px;
		}
		
		.menu-item {
			padding: 14px 16px;
		}
	}
</style>
